//
//  DeviceTool.m
//  UsLink
//
//  Created by admin on 2018/5/11.
//  Copyright © 2018年 admin. All rights reserved.
//

#import "DeviceTool.h"
#import <MessageUI/MessageUI.h>
#import <AVFoundation/AVFoundation.h>
#import "HelenHttpClient.h"
#import "UIImage+WB.h"

@interface DeviceTool()<MFMessageComposeViewControllerDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property(copy,nonatomic) void(^completionHandler)(UIImage *image);

@end

@implementation DeviceTool

+ (instancetype)shareInstance{
    static DeviceTool *_instance = nil ;
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        if (_instance == nil) {
            _instance = [[DeviceTool alloc] init];
        }
    });
    return _instance;
}


//打电话
- (void)callWithPhoneNumber:(NSString *)phoneNumber
{
    UIWebView *webView = [[UIWebView alloc] init];
    NSString *string = [NSString stringWithFormat:@"tel://%@",phoneNumber];
    NSURL *url = [NSURL URLWithString:string];
    [webView loadRequest:[NSURLRequest requestWithURL:url]];
    [_target.view addSubview:webView];
}



//发短信
- (void)messageWithPhones:(NSArray *)phones title:(NSString *)title body:(NSString *)body
{
    if( [MFMessageComposeViewController canSendText] ) {
        MFMessageComposeViewController * controller = [[MFMessageComposeViewController alloc] init];
        controller.recipients = phones;
        controller.navigationBar.tintColor = [UIColor redColor];
        controller.body = body;
        controller.messageComposeDelegate = self;
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.target presentViewController:controller animated:YES completion:nil];
        });
        [[[[controller viewControllers] lastObject] navigationItem] setTitle:title]; //修改短信界面标题
        
    } else {
        UIAlertController *ac = [UIAlertController alertControllerWithTitle:@"提示信息" message:@"该设备不支持短信功能" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"好，我知道了" style:UIAlertActionStyleCancel handler:nil];
        [ac addAction:action];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.target presentViewController:ac animated:YES completion:nil];
        });
        
    }
}



//发短信
-(void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
    [_target dismissViewControllerAnimated:YES completion:nil];
    switch (result) {
        case MessageComposeResultSent: //信息传送成功
            NSLog(@"信息发送成功");
            break;
        case MessageComposeResultFailed: //信息传送失败
            NSLog(@"信息传送失败"); break;
        case MessageComposeResultCancelled: //信息被用户取消传送
            NSLog(@"信息被用户取消传送");
        break;
            
        default:
        break;
    }
}


// 开始拍照
-(void)takePhotoWithCompletionHandler:(void (^)(UIImage *))completionHandler
{
    _completionHandler = completionHandler;
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        picker.allowsEditing = YES;
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        //先检查相机可用是否
        BOOL cameraIsAvailable = [self checkCamera];
        if (YES == cameraIsAvailable) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.target presentViewController:picker animated:YES completion:nil];
            });
            
        }else {
            
            UIAlertController *ac = [UIAlertController alertControllerWithTitle:@"提示" message:@"请在iPhone的“设置-隐私-相机”选项中，允许本应用程序访问你的相机。" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"好，我知道了" style:UIAlertActionStyleCancel handler:nil];
            [ac addAction:action];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.target presentViewController:ac animated:YES completion:nil];
            });
        }
    }
}



// 打开本地相册
-(void)localPhotoWithCompletionHandler:(void (^)(UIImage *))completionHandler
{
    _completionHandler = completionHandler;
    //本地相册不需要检查，因为UIImagePickerController会自动检查并提醒
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    //设置选择后的图片可被编辑
    picker.allowsEditing = YES;
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.target presentViewController:picker animated:YES completion:nil];
    });
    
}


//检查相机是否可用
- (BOOL)checkCamera
{
    NSString *mediaType = AVMediaTypeVideo;
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    if(AVAuthorizationStatusRestricted == authStatus || AVAuthorizationStatusDenied == authStatus){
        //相机不可用
        return NO;
    }else{ //相机可用
        return YES;
    }
}


//压缩图片质量
-(UIImage *)reduceImage:(UIImage *)image percent:(float)percent
{
    NSData *imageData = UIImageJPEGRepresentation(image, percent);
    UIImage *newImage = [UIImage imageWithData:imageData];
    return newImage;
}


//压缩图片尺寸
- (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
    CGFloat scale = [[UIScreen mainScreen] scale];
    UIGraphicsBeginImageContextWithOptions(newSize, NO, scale);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext(); return newImage;
}




#pragma mark - #pragma mark UIImagePickerControllerDelegate Call Back Implementation
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"]) {
        NSString *key = nil;
        if (picker.allowsEditing) {
            key = UIImagePickerControllerEditedImage;
            
        }else {
            key = UIImagePickerControllerOriginalImage;
            
        }
        
        //获取图片
        UIImage *image = [info objectForKey:key];
//        if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
            // 固定方向

//            //压缩图片质量
//            image = [self reduceImage:image percent:0.1];
//            CGSize imageSize = image.size;
//            imageSize.height = 320;
//            imageSize.width = 320;
//            //压缩图片尺寸
            image = [self imageWithImageSimple:image scaledToSize:CGSizeMake(320, 320)];
        
//        }
        
        //block回调
        !self.completionHandler ? :self.completionHandler(image);
        //关闭相册界面
        [picker dismissViewControllerAnimated:YES completion:nil];

    }
    
}


@end
